﻿using UnityEngine;
using System.Collections;

public class InitialMenu : MonoBehaviour {
	public ServerPrimary server;

	public string connectionIP = "127.0.0.1";
	public int connectionPort = 25001;
	
	void Awake() {
		Debug.Log ("InitialMenu.Awake().");
		DontDestroyOnLoad (transform.root.gameObject); // persist this object through all scenes
	} // end event

	void OnGUI()
	{
		if (Network.peerType == NetworkPeerType.Disconnected || (!server.IsOpen && Network.peerType == NetworkPeerType.Server))
		{
			GUI.Label(new Rect(10, 10, 300, 20), "Status: Disconnected");
			if (GUI.Button(new Rect(10, 30, 120, 20), "Client Connect"))
			{
				Debug.Log ("Connecting to " + connectionIP);
				Debug.Log (Network.Connect(connectionIP, connectionPort));
			}
			if (GUI.Button(new Rect(10, 50, 120, 20), "Initialize Server"))
			{
				if (server.HasOpened) {
					Debug.Log ("Server resumed from previous initialization.");
					server.IsOpen = true;
				}
				else
				{
					Debug.Log ("Initializing on port: " + connectionPort);
					NetworkConnectionError e = Network.InitializeServer(ServerPrimary.MAX_CONNECTIONS, connectionPort, false);

					if (NetworkConnectionError.NoError != e)
						Debug.Log ("Initialization failed: " + e);
					else {
						Debug.Log ("Initialization successful.");
						server.IsOpen = true;
					}
				}
			}
		}
		else if (Network.peerType == NetworkPeerType.Client)
		{
			GUI.Label(new Rect(10, 10, 300, 20), "Status: Connected as Client");
			if (GUI.Button(new Rect(10, 30, 120, 20), "Disconnect"))
			{
				Network.Disconnect(200);
			}
		}
		else if (Network.peerType == NetworkPeerType.Server)
		{
			GUI.Label(new Rect(10, 10, 300, 20), "Status: Connected as Server");
			if (GUI.Button(new Rect(10, 30, 120, 20), "Disconnect"))
			{
				Debug.Log ("Closed server to clients.");
				server.IsOpen = false;
			}
			if (GUI.Button (new Rect(10, 50, 120, 20), "Let's Go!"))
			{
				server.CurrentState = ServerPrimary.GameState.MAPPING;
			}
		}
	}
}
